//
//  TravelNotesDetailViewController.m
//  面包旅行
//
//  Created by dllo on 15/5/21.
//  Copyright (c) 2015年 jakf_MacBook. All rights reserved.
//

#import "TravelNotesDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <AFNetworking/AFNetworking.h>
#import "NotesDetailCell.h"
#import "NotesInfoCell.h"
#import "NotesModel.h"
//#import "ConnectModle.h"
//#import "ConnectWeb.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
@interface TravelNotesDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation TravelNotesDetailViewController

- (void)dealloc
{
    
    [self.array release];
    [self.daysArray release];
    [self.waypointsArray release];
    [self.noteTableView release];
    [self.cellCount release];
    [self.dictionary release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.width = [UIScreen mainScreen].bounds.size.width;
        self.daysArray = [NSMutableArray array];
        self.waypointsArray = [NSMutableArray array];
        self.dictionary = [NSMutableDictionary dictionary];
        self.array = [NSMutableArray array];
//        self.notes = [[NotesModel alloc] init];
//        [self.notes release];
    }
    return self;
}

#pragma mark 游记正文
- (void)createNoteTableView
{
    self.noteTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.noteTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.noteTableView.dataSource = self;
    self.noteTableView.delegate = self;
    self.noteTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.noteTableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"AN = %ld", self.cellCount.integerValue + 1);
    return self.cellCount.integerValue + 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellName = @"cell";
    
    if (indexPath.row == 0) {
        NotesInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"once"];
        if (!cell) {
            cell = [[[NotesInfoCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"once"] autorelease];
        }
#pragma mark 赋值
        cell.titleLabel.text = [self.dictionary objectForKey:@"name"];
        
        NSURL *mapUrl = [NSURL URLWithString:[self.dictionary objectForKey:@"trackpoints_thumbnail_image"]];
        [cell.mapImageView sd_setImageWithURL:mapUrl];
        
        NSString *str = [NSString stringWithFormat:@"%@   %@天 ",[self.dictionary objectForKey:@"first_day"], [self.dictionary objectForKey:@"day_count"]];
        cell.dayLabel.text = str;
        
        NSMutableDictionary *userDic = [self.dictionary objectForKey:@"user"];
        NSURL *userUrl = [NSURL URLWithString:[userDic objectForKey:@"avatar_m"]];
        [cell.userImageView sd_setImageWithURL:userUrl];
        
        NSNumber *distance = [self.dictionary objectForKey:@"mileage"];
      
        cell.distanceLabel.text = [NSString stringWithFormat:@"------------ %.2lf公里 ------------", [distance doubleValue]];
        
        NSArray *cityArray = [self.dictionary objectForKey:@"cities"];
        self.text = [NSMutableString string];

        for (NSString *str in cityArray) {
            NSLog(@"str:%@", str);
            [self.text appendString:str];
            [self.text appendString:@"  "];
        }
        NSLog(@"----------%@", _text);
        cell.destinationLabel.text = _text;
        cell.distanceLabel.textAlignment = NSTextAlignmentCenter;
        
        NSArray *arr1 = [_dictionary objectForKey:@"covered_countries"];
        NSDictionary *dic1 = [arr1 objectAtIndex:0];
        NSURL *cityUrl = [NSURL URLWithString:[dic1 objectForKey:@"icon"]];
        [cell.countryImageview sd_setImageWithURL:cityUrl];
        
        return cell;
    
#pragma mark 正文cell
    } else {
    NotesDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[[NotesDetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"] autorelease];
    }
        self.notes = _array[indexPath.row - 1];
        cell.photoWeb = self.notes.photo;
        // 对是否有图片进行判断[self.notes.photo_info isKindOfClass:[NSNull class]]
        NSDictionary *photo_infoDic = self.notes.photo_info;
        if ([self.notes.photo isEqualToString:@""] || photo_infoDic == nil ) {
            // 图片不存在, 赋值文字
            
            cell.notesLabel.text = self.notes.text;
            cell.notesLabel.numberOfLines = 0;
            cell.poi = self.notes.poi;
            cell.country = self.notes.country;
            cell.city = self.notes.city;
            cell.province = self.notes.province;
            cell.local_time = self.notes.local_time;
            cell.photo.image = nil;
            cell.photo_info = nil;
            return cell;
        }
        else {
            cell.photo_info = self.notes.photo_info;
            
            NSURL *url = [NSURL URLWithString:self.notes.photo];
            [cell.photo sd_setImageWithURL:url placeholderImage:nil];
            
            cell.poi = self.notes.poi;
            cell.notesLabel.text = self.notes.text;
            cell.notesLabel.numberOfLines = 0;
            cell.country = self.notes.country;
            cell.city = self.notes.city;
            cell.local_time = self.notes.local_time;
            cell.province = self.notes.province;
            NSLog(@"游记正文 = %@", self.notes.text);
            
            return cell;
        }
        
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 300;
    }
    self.notes = _array[indexPath.row - 1];
    NSString *str = self.notes.text;
    // 对是否有图片进行判断
    NSDictionary *photo_infoDic = self.notes.photo_info;
    if ([self.notes.photo isEqualToString:@""] || photo_infoDic == nil) {
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        CGRect rect = [str boundingRectWithSize:CGSizeMake(WIDTH * 325 / 375, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + WIDTH * 120 / 375;
    } else {
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(WIDTH * 325 / 375, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    NSNumber *num1 = [self.notes.photo_info objectForKey:@"h"];
    NSLog(@"num1 ====== %@", num1);
    CGFloat height = [num1 floatValue];
    NSLog(@"height ====== %f", height);
    NSNumber *num2 = [self.notes.photo_info objectForKey:@"w"];
    CGFloat width = [num2 floatValue];
    CGFloat imageHeight = WIDTH * 300 / 375 * height / width;
    
    
    return rect.size.height + WIDTH * 120 / 375 + imageHeight;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.translucent = NO;
    

#pragma mark 网络请求数据
    NSMutableString *notesWeb = [NSMutableString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/", self.webId];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:notesWeb parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSDictionary dictionary];
        dic = responseObject;
        self.cellCount = [dic objectForKey:@"waypoints"];
        NSLog(@"%@", _cellCount);
        
        self.dictionary = [NSMutableDictionary dictionaryWithDictionary:dic];
        
        self.daysArray = [self.dictionary objectForKey:@"days"];
        for (NSMutableDictionary *aDic in self.daysArray) {
            self.waypointsArray = [aDic objectForKey:@"waypoints"];
            
            for (NSMutableDictionary *bDic in self.waypointsArray) {
                NotesModel *notes = [[NotesModel alloc] init];
                [notes setValuesForKeysWithDictionary:bDic];
                [self.array addObject:notes];
                
                [notes release];
            }
        }
        
        [_noteTableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
    [self createNoteTableView];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
